<template>
  <j-modal :title='title' :width='800' :visible='visible' :confirmLoading='confirmLoading' switchFullscreen
    @ok='handleOk' @cancel='handleCancel' cancelText='关闭'>
    <a-divider style='font-weight: 600;margin-top: 0px;' orientation='left'>基本信息</a-divider>
    <a-spin :spinning='confirmLoading'>
      <a-form :form='form'>
        <a-col :md='12' :sm='24'>
          <a-form-item label='选择人员' v-if='!itemShow' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input-search v-decorator="['visitUserRealName',validatorRules.visitUserRealName]" placeholder='请选择协访人员'
              :disabled='disableSubmit' readOnly enter-button @search="productSearch2('superiorUser')" />
            <a-input v-decorator="[ 'visitUserName', {}]" readOnly type='hidden' />
          </a-form-item>
        </a-col>
        <a-col :md='12' :sm='24'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='人员职位'>
            <a-input v-decorator="['visitPosName']" :disabled='true' />
          </a-form-item>
        </a-col>
        <a-col :md='12' :sm='24'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属组织'>
            <a-input :disabled='true' v-decorator="['departName']" />
          </a-form-item>
        </a-col>
        <a-col :md='12' :sm='24'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='循环日期'>
            <a-range-picker :placeholder="['开始时间','结束时间']" :format="'YYYY-MM-DD'" :valueFormat="'YYYY-MM-DD'"
              v-decorator="['visitDates', validatorRules.visitDates]" @change='dateRangeChange'></a-range-picker>
          </a-form-item>
        </a-col>
        <a-divider orientation='left' style='font-weight: 400;margin-top: 0px;'>门店</a-divider>

        <a-button style='margin: 10px 30px 0px 30px;' @click="handleConfig(record)" type='primary'
          v-if='!disableSubmit'>新增
        </a-button>
        <div style='padding: 10px 20px;'>
          <a-table ref='table' :columns='columns' :dataSource='dataSource2' :rowSelection='{selectedRowKeys:selectedRowKeys, onChange: onSelectChange1}' :scroll='{x:400,y:240 }' bordered
            rowKey='id' size='middle'
            @change='handleTableChange'>
            <span slot='action' slot-scope='text, record'>
              <a style='color: red;' @click='handleDelete2(record)' v-if='!disableSubmit'>删除</a>
            </span>
          </a-table>
        </div>

        <a-divider orientation='left' style='font-weight: 400;margin-top: 0px;'>经销商</a-divider>
        <a-button v-if='!disableSubmit' style='margin: 10px 30px 0px 30px;' type='primary'
                  @click="handleConfigTer(record)">新增
        </a-button>
        <div style='padding: 10px 20px;'>
          <a-table ref='table' :columns='columns2' :dataSource='dataSource' :rowSelection='{selectedRowKeys:selectedRowKeys2, onChange: onSelectChange2}' :scroll='{x:400,y:240 }' bordered
                   rowKey='id' size='middle'
                   @change='handleTableChange'>
            <span slot='action' slot-scope='text, record'>
              <a v-if='!disableSubmit' style='color: red;' @click='handleDelete(record)'>删除</a>
            </span>
          </a-table>
        </div>
        <my-shuttle-modal
          ref='orgShuttleModal'
          :positionCode='positionCode'
          :columns='orgColumns'
          :columns2='orgColumns2'
          :searchConfig='orgSearchConfig'
          keyVal='custCode'
          leftUrl='/customerExtendController/findPageListByPositionCode '
          title='选择经销商'
          @chooseOk='chooseOk'
        ></my-shuttle-modal>
        <my-shuttle-modal
          :positionCode='positionCode'
          ref='cusShuttleModal'
          :columns='cusColumns'
          :columns2='cusColumns2'
          :searchConfig='cusSearchConfig'
          keyVal='terminalCode'
          leftUrl='/cnTerminalExtendController/findPageListByPositionCode '
          title='选择门店'
          @chooseOk='chooseOk2'
        ></my-shuttle-modal>
      </a-form>

    </a-spin>
    <StorePlanMod ref="ConfigPosCust" modal-width='90%' @ok='dataUserRess'></StorePlanMod>
    <StorePlanMod modal-width='90%' ref="ConfigModal" @ok="saveUserRelation"></StorePlanMod>
<!--    <proChose ref="prochoose" name="商品分类" v-bind='modalProps1' @okbro="okbropro1"></proChose>-->
<!--    <proChose ref="prochoose1" name="线路组" v-bind='modalProps' @okbro="okbropro"></proChose>-->
    <proChose ref='prochoose2' v-bind='modalProps' @okbro='okbropro2'></proChose>
  </j-modal>
</template>

<script>
  import {
    httpAction,
    postAction
  } from '@/api/manage'
  import proChose from '@comp/cn-components/ProChose'

  import pick from 'lodash.pick'
  import chooseModal from '@/components/cn-components/ChooseModal'
  import JTreeSelect from '@/components/cn-form/JTreeSelect'
  import WedPalnMakingMod from './WedPalnMakingMod.vue'
  import StorePlanMod from './StorePlanMod.vue'
  import myShuttleModal from '@/components/cn-components/CnShuttleModal'
  export default {
    name: 'SfaSignConfigModal',
    components: {
      JTreeSelect,
      chooseModal,
      proChose,
      WedPalnMakingMod,
      StorePlanMod,
      myShuttleModal
    },
    data() {
      return {
        name: '',
        time:'星期一',
        title: '操作',
        objs: [],
        value: 1,
        positionCode:'', //职位编码
        dataSource: [],
        dataSource2: [],
        lineVos: [],
        visible: false,
        model: {},
        labelCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 5
          }
        },
        wrapperCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 16
          }
        },
        // 门店
        columns: [
          {
            title: '门店编码',
            align: 'center',
            dataIndex: 'terminalCode'
          },
          {
            title: '门店名称',
            align: 'center',
            dataIndex: 'terminalName'
          },
          {
            title: '操作',
            dataIndex: 'action',
            fixed: 'right',
            align: 'center',
            width: 150,
            scopedSlots: {
              customRender: 'action'
            }
          }
        ],
        //门店弹框搜索条件
        cusSearchConfig:[
          {
            type:'input',


            placeholder:'门店编号',
            name:'terminalCode'
          },
          {
            type:'input',
            placeholder:'门店名称',
            name:'terminalName'
          }
        ],
        cusColumns: [
          {
            title: '门店编码',
            align: 'center',
            dataIndex: 'terminalCode'
          },
          {
            title: '门店名称',
            align: 'center',
            dataIndex: 'terminalName'
          }
        ],
        cusColumns2: [
          {
            title: '门店编码',
            align: 'center',
            dataIndex: 'terminalCode'
          },
          {
            title: '门店名称',
            align: 'center',
            dataIndex: 'terminalName'
          },
          {
            title: '操作',
            dataIndex: 'action',
            // fixed: 'right',
            align: 'center',
            scopedSlots: {
              customRender: 'delete'
            }
          }
        ],
        //线路组
        columns2: [
          {
            title: '经销商编码',
            align: 'center',
            dataIndex: 'code'
          },
          {
            title: '经销商名称',
            align: 'center',
            dataIndex: 'name'
          },
          {
            title: '操作',
            dataIndex: 'action',
            fixed: 'right',
            align: 'center',
            width: 150,
            scopedSlots: {
              customRender: 'action'
            }
          }
        ],
        orgSearchConfig:[
          {
            type:'input',
            placeholder:'经销商编号',
            name:'code'
          },
          {
            type:'input',
            placeholder:'经销商名称',
            name:'name'
          }
        ],
        orgColumns: [

          {
            title: '经销商编码',
            align: 'center',
            dataIndex: 'custCode'
          },
          {
            title: '经销商名称',
            align: 'center',
            dataIndex: 'custName'
          }
        ],
        orgColumns2: [
          {
            title: '经销商编码',
            align: 'center',
            dataIndex: 'custCode'
          },
          {
            title: '经销商名称',
            align: 'center',
            dataIndex: 'custName'
          },
          {
            title: '操作',
            dataIndex: 'action',
            // fixed: 'right',
            align: 'center',
            scopedSlots: {
              customRender: 'delete'
            }
          }
        ],
        /* table选中keys*/
        selectedRowKeys: [],
        /* table选中records*/
        selectionRows: [],
        selectedRowKeys2: [],
        /* table选中records*/
        selectionRows2: [],
        positionsColumns: [
          // {
          //   title: '#',
          //   key: 'rowIndex',
          //   width: 60,
          //   align: 'center',
          //   customRender: function(t, r, index) {
          //     return parseInt(index) + 1
          //   }
          // },
          {
            title: '门店编码',
            align: 'center',
            dataIndex: 'terminalCode'
          },
          {
            title: '门店名称',
            align: 'center',
            dataIndex: 'terminalName'
          },
          {
            title: '操作',
            dataIndex: 'action',
            fixed: 'right',
            align: 'center',
            width: 150,
            scopedSlots: {
              customRender: 'action'
            }
          }
        ],
        // productSearch(status) {
        //   this.$refs.prochoose1.rowKey = 'id'
        //   let formconfig = [
        //     {
        //       key: 'groupCode',
        //       label: '分类编号'
        //     },
        //     {
        //       key: 'groupName',
        //       label: '分类名称'
        //     }
        //   ]
        //   let tableconfig = {
        //     columns: [
        //       {
        //         title: '分类编号',
        //         align: 'left',
        //         dataIndex: 'groupCode',
        //         width: 120,
        //         ellipsis: true
        //       },
        //       {
        //         title: '分类名称',
        //         align: 'left',
        //         dataIndex: 'groupName',
        //         width: 120,
        //         ellipsis: true
        //       }
        //     ],
        //     list: window._CONFIG['domianSfaURL'] + '/visit/sfaVisitGroupController/findPageList',
        //     multiple: false,
        //     columW: 10
        //   }
        //
        //   this.name = '用户'
        //   let dataSource = []
        //   if (this.form.getFieldValue('superiorUser')) {
        //     dataSource = [{
        //       userName: this.form.getFieldValue('superiorUser'),
        //       realName: this.form.getFieldValue('classifyCode')
        //     }]
        //   }
        //   console.log(dataSource)
        //   this.$refs.prochoose1.edit(formconfig, tableconfig, 'superiorUser', 'realsname', dataSource)
        // },
        // productSearch1(status) {
        //   this.$refs.prochoose.rowKey = 'id'
        //   let formconfig = [
        //     {
        //       key: 'groupCode',
        //       label: '分类编号'
        //     },
        //     {
        //       key: 'groupName',
        //       label: '分类名称'
        //     }
        //   ]
        //   let tableconfig = {
        //     columns: [
        //       {
        //         title: '线路编号',
        //         align: 'left',
        //         dataIndex: 'groupCode',
        //         width: 120,
        //         ellipsis: true
        //       },
        //       {
        //         title: '分类名称',
        //         align: 'left',
        //         dataIndex: 'groupName',
        //         width: 120,
        //         ellipsis: true
        //       }
        //     ],
        //     list: window._CONFIG['domianSfaURL'] + '/visit/sfaVisitGroupController/findPageList',
        //     multiple: false,
        //     columW: 10
        //   }
        //
        //   this.name = '用户'
        //   let dataSource = []
        //   if (this.form.getFieldValue('superiorUser')) {
        //     dataSource = [{
        //       userName: this.form.getFieldValue('superiorUser'),
        //       realName: this.form.getFieldValue('classifyCode')
        //     }]
        //   }
        //   console.log(dataSource)
        //   this.$refs.prochoose.edit(formconfig, tableconfig, 'superiorUser', 'realsname', dataSource)
        // },
        productSearch2(status) {
          this.$refs.prochoose2.rowKey = 'id'
          let formconfig = [{
              key: 'userName',
              label: '用户账户'
            },
            {
              key: 'realName',
              label: '用户名称'
            }
          ]
          let tableconfig = {
            columns: [{
                title: '用户账户',
                align: 'left',
                dataIndex: 'userName',
                width: 120,
                ellipsis: true
              },
              {
                title: '用户名称',
                align: 'left',
                dataIndex: 'realName',
                width: 120,
                ellipsis: true
              }
            ],
            list: window._CONFIG['domianURL'] + '/cnUserController/getPageListUser',

            multiple: false,
            columW: 10
          }

          this.name = '用户'
          let dataSource = []
          if (this.form.getFieldValue('superiorUser')) {
            dataSource = [{
              userName: this.form.getFieldValue('superiorUser'),
              realName: this.form.getFieldValue('realsname')
            }]
          }
          this.$refs.prochoose2.edit(formconfig, tableconfig, 'superiorUser', 'realsname', dataSource)
        },
        rule: [{
          count: 0,
          actCode: '',
          orderNum: '',
          discount: '',
          gifts: []
        }],
        chara: [],
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules: {
          visitDates:{
            rules: [{
              required: true,
              message: ''
            }]
          },
          visitUserRealName: {
            rules: [{
              required: true,
              message: ''
            }]
          },
          classifyName:{
            rules: [{
              required: true,
              message: ''
            }]
          },
          classifytotName:{
            rules: [{
              required: true,
              message: ''
            }]
          },
        },
        url: {
          add: window._CONFIG['domianSfaURL'] + '/visit/sfaVisitLineController/saveOrUpdate',
          savePosCust: window._CONFIG['domainURL'] + '/cnTerminalExtendController/saveTerminalExtend',
          saveUserRelation: window._CONFIG['domianURL'] + '/customerExtendController/saveExtendPos',
        }
      }
    },
    computed: {
      modalProps() {
        return {
          name: this.name
        }
      },
      modalProps1() {
        return {
          name: this.name
        }
      }
    },
    methods: {
      //经销商
      onSelectChange1(selectedRowKeys, selectionRows) {
          this.selectedRowKeys = selectedRowKeys
          this.selectionRows = selectionRows
      },
      // 线路组
      onSelectChange2(selectedRowKeys, selectionRows) {
        this.selectedRowKeys2 = selectedRowKeys
        this.selectionRows2 = selectionRows
      },
      chooseOk(e) {
        let key = this.dataSource.map(item => {
          return item.code
        })
        console.log(e)
        let that = this
        e.forEach(item => {
          if (key.indexOf(item.custCode) == -1) {
            item.code = item.custCode
            item.name = item.custName
            this.dataSource.push(item)
          }
        })
      },
      //门店新增弹窗确认
      chooseOk2(e){
        let key = this.dataSource2.map(item => {
          return item.code
        })
        console.log(e)
        let that = this
        e.forEach(item => {
          if (key.indexOf(item.terminalCode) == -1) {
            item.code = item.terminalCode
            item.name = item.terminalName
            this.dataSource2.push(item)
          }
        })
      },
      okbropro1(val, status, status2) {
        let objs = JSON.parse(JSON.stringify(val[0]))
        console.log(objs)
        this.form.setFieldsValue({
          classifyName: objs.groupName,

        })
        this.model.classifyCode=objs.groupCode
      },
      okbropro(val, status, status2) {
        let objs = JSON.parse(JSON.stringify(val[0]))
        console.log(objs)
        this.form.setFieldsValue({
          classifytotName: objs.groupName,

        })
        this.model.classifyCode=objs.groupCode
      },
      okbropro2(val, status, status2) {
        let objs = JSON.parse(JSON.stringify(val[0]))
        this.objs = objs
        this.form.setFieldsValue({
          visitUserName: objs.userName,
          visitUserRealName: objs.realName,
          visitPosName: objs.positionName,
          visitPosCode: objs.positionCode,
          departName: objs.departName,
          departCode: objs.departCode,
        })
        this.positionCode = this.objs.positionCode
      },
      showModal(groupCode) {
        this.visible = true;
        this.reqCode = groupCode
        this.queryParam.groupCode = groupCode
      },
      saveUserRelation(params) {
        console.log(params.posExtendVos)
        this.dataSource2 = params.posExtendVos
        // postAction(this.url.saveUserRelation, this.dataSource2).then(async (res) => {
        //   if (res.success) {
        //     this.$message.success(res.message)
        //     await this.loadData()
        //     this.$refs.ConfigModal.close()
        //   } else {
        //     this.$message.warning(res.message)
        //   }
        // }).finally(() => {
        //   this.$refs.ConfigModal.confirmLoading = false
        //   //that.close();
        // })

      },
      dataUserRess(params) {
        console.log(params)
        this.dataSource = params.posExtendVos
      },
      //经销商删除
      handleDelete(e) {
          let key = this.dataSource.map(item => {
            return item.id
          })
          this.dataSource.splice(key.indexOf(e.id), 1)

      },
      //门店删除
      handleDelete2(e) {
          let key = this.dataSource2.map(item => {
            return item.id
          })
          this.dataSource2.splice(key.indexOf(e.id), 1)
      },
      // handleDelete2(record) {
      //   for (let i = 0; i < this.dataSource2.length; i++) {
      //     if (this.dataSource2[i].terminalCode == record.terminalCode) {
      //       this.dataSource2.splice(i, 1)
      //     }
      //   }
      //   // this['dataSource2'].removeByCode(record,'id')
      //   // this[this.activeKey + 'sData'].removeByCode(record, this.activeKey + 'Code')
      //   // this[this.activeKey + 'SelectionRows'].removeByCode(record, this.activeKey + 'Code')
      //   // this[this.activeKey + 'SelectedRowKeys'].remove(record[this.activeKey + 'Code'])
      // },
      //上级用户选择
      productSearch(status) {
        this.$refs.prochoose.rowKey = 'id'
        let formconfig = [{
            key: 'userName',
            label: '用户账户'
          },
          {
            key: 'realName',
            label: '用户名称'
          }
        ]
        let tableconfig = {
          columns: [{
              title: '用户账户',
              align: 'left',
              dataIndex: 'userName',
              width: 120,
              ellipsis: true
            },
            {
              title: '用户名称',
              align: 'left',
              dataIndex: 'realName',
              width: 120,
              ellipsis: true
            }
          ],
          list: window._CONFIG['domianURL'] + '/cnUserController/getPageListUser',

          multiple: false,
          columW: 10
        }

        this.name = '用户'
        let dataSource = []
        if (this.form.getFieldValue('superiorUser')) {
          dataSource = [{
            userName: this.form.getFieldValue('superiorUser'),
            realName: this.form.getFieldValue('realsname')
          }]
        }
        this.$refs.prochoose.edit(formconfig, tableconfig, 'superiorUser', 'realsname', dataSource)
      },
      //有效期时间
      addInclude() {
        this.$refs.chooseModal1.show()
      },
      add() {
        this.edit({})
      },
      edit(record,id) {
        this.form.resetFields()
        this.model = Object.assign({}, record)
        this.visible = true
        this.model.isRoll = this.model.isRoll + ''
        this.model.isControl = this.model.isControl + ''
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'jobStatus', 'signOutStart', 'Position',
            'orgCode', 'visitor'))
        })
      },
      handleConfigTer() {
        this.dataSource.forEach(item => {
          this.$refs.orgShuttleModal.dataSource2.push({ custName: item.name, custCode: item.code })
        })
        this.$refs.orgShuttleModal.visible = true
        this.$refs.orgShuttleModal.loadData()
      },
      handleConfig() {
        this.dataSource2.forEach(item => {
          this.$refs.cusShuttleModal.dataSource2.push({ terminalName: item.name, terminalCode: item.code })
        })
        this.$refs.cusShuttleModal.visible = true
        this.$refs.cusShuttleModal.loadData()
      },
      async handleWhite(record) {
        this.currentWhite = record
        this.$refs.WhiteModal.showModal(record.terminalCode)
      },
      handelSaveWhite(typeList, productList, positionList, record) {

        let that = this
        const tList = typeList.map(type => Object.assign({
          code: type.code,
          name: type.name,
          dataType: 3
        }))
        const pList = productList.map(type => Object.assign({
          code: type.code,
          name: type.name,
          remarks: type.imgUrl,
          dataType: 4
        }))
        const positions = positionList.map(type => Object.assign({
          code: type.visitPosCode,
          name: type.visitPosName,
          dataType: 5
        }))
        if (!record.extendVos) record.extendVos = []
        const retainRows = record.extendVos.filter(row => [1, 2].includes(Number(row.dataType)))
        record.extendVos = [...retainRows, ...tList, ...pList, ...positions]
        that.loadData()
        postAction(window._CONFIG['domianURL'] + '/cnTerminalController/saveTerExtend', record).then(async (res) => {
          if (res.success) {
            that.$message.success(res.message)
            this.$refs.WhiteModal.showModal('')
            this.$refs.WhiteModal.close()
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.$refs.WhiteModal.confirmLoading = false
          //that.close();
        })
      },
      savePosCust(params) {

        postAction(this.url.savePosCust, params).then(async (res) => {
          if (res.success) {
            this.$message.success(res.message)
            await this.loadData()
            this.$refs.ConfigPosCust.close()
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.$refs.ConfigPosCust.confirmLoading = false
          //that.close();
        })
      },
      close() {
        this.$emit('close')
        this.form = this.$form.createForm(this),
        this.visible = false
        this.dataSource =[]
        this.dataSource2 =[]
      },

      handleOk() {
        const that = this
        // 触发表单验证
        //经销商
        let dataSource = this.dataSource.map(type => Object.assign({
          clientCode: type.custCode,
          clientName: type.custName,
          longitude:type.longitude,
          latitude:type.latitude,
          clientType: 2
        }))
        //门店
        let dataSource2 = this.dataSource2.map(type => Object.assign({
          clientCode: type.terminalCode,
          clientName: type.terminalName,
          longitude:type.longitude,
          latitude:type.latitude,
          clientType: 1
        }))
        // console.log(dataSource,dataSource2)
        this.lineVos = dataSource2.concat(dataSource)
        console.log(this.lineVos)
        this.form.validateFields((err, values) => {
          console.log(values)
            that.confirmLoading = true
            let httpurl = ''
            httpurl = this.url.add
            let method = ''
            method = 'post'
            let formData = Object.assign(this.model, values)
            formData.visitPosCode = this.objs.positionCode
            formData.orgCode = this.objs.departCode
            formData.lineVos = this.lineVos
            formData.operType = 1
            console.log(formData)
            //时间格式化
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
              that.close()
            })

        })
      },
      handleCancel() {
        this.close()
      }
    }
  }
</script>

<style scoped>

</style>
